import instance from "@/main";
import store from "@/store";

/**
 * @param {Array} routerlist 处理后端返回的路由数据，变成需要的格式
 */

export function formatRouter(routerlist) {
  const router = [];
  try {
    routerlist.forEach(item => {
      let r = {
        id: item.id,
        path: item.path,
        meta: {},
        component: () =>
          item.moduleUrl === "layout"
            ? import("@/page/basic-layout")
            : item.moduleUrl === "authLayout"
            ? import("@/page/auth-layout")
            : item.moduleUrl === "contentLayout"
            ? import("@/page/content-layout")
            : import(`@/views/${item.moduleUrl}`)
      };
      if (item.webParentId) {
        r = {
          ...r,
          webParentId: item.webParentId
        };
      }
      if (item.flag) {
        r = {
          ...r,
          name: item.flag
        };
      }
      if (item.children && item.children !== []) {
        const children = formatRouter(item.children);
        // 保存权限
        r = {
          ...r,
          children: children
        };
      }
      if (item.redirect) {
        r = {
          ...r,
          redirect: item.redirect
        };
      }
      if (item.resourceName) {
        r = {
          ...r,
          meta: {
            ...r.meta,
            title: item.resourceName
          }
        };
      }
      if (item.icon) {
        r = {
          ...r,
          meta: {
            ...r.meta,
            icon: item.icon
          }
        };
      }
      if (item.hidden !== undefined) {
        r = {
          ...r,
          hidden: item.hidden === 0 ? false : true
        };
      }
      if (item.affiliation) {
        r = {
          ...r,
          meta: {
            ...r.meta,
            menuName: item.affiliation
          }
        };
      }
      router.push(r);
    });
  } catch (error) {
    console.error(error);
    return [];
  }
  // console.log(router)
  return router;
}

/*
 * @export 根据后台返回的按钮权限列表判断是否显示
 */

export function handleBtn(val) {
  let asyncRouter = store.state.router.asyncRouter;
  let btnPermission = store.state.router.btnPermission;
  let routeName = instance.$route.name;
  let route = asyncRouter.filter(i => i.flag === routeName);
  let res;
  if (route.length === 0) {
    res = [];
  } else {
    let btns = btnPermission.filter(
      i => i.webParentId === route[0].id && i.type !== 0 && i.type !== 2
    );
    let flags = btns.map(i => i.flag);
    res = flags.indexOf(val) !== -1;
  }
  return res;
}

/*
 * @export 处理没有具体页面的按钮是否显示
 */
export function verifyBtn(val) {
  let btnPermission = store.state.router.btnPermission;
  btnPermission = btnPermission.map(i => i.flag);
  return btnPermission.indexOf(val) !== -1;
}
